﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.ContentHub.CustomFields;
using MS.InformationManagement.Core.TransactionsResponse;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using System.Collections;
using MS.InformationManagement.Support.Enums;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.ContentHub.ObjectDef.CustomFields;
using Microsoft.SharePoint.Utilities;

namespace MS.InformationManagement.Core.Documentset
{
    public class RadicadoPersonaSalidaActions : BaseDocumentSet<RadicadoPersonaSalida>
    {
        #region Constructors

        public RadicadoPersonaSalidaActions(RadicadoPersonaSalida radicado) : base(radicado) { }

        public RadicadoPersonaSalidaActions() { }

        #endregion

        #region Properties

        //public Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet CurrentDocumentSet { get; set; }

        #endregion

        public override string NewRadicado(SPFolder parentFolder)
        {
            Hashtable requiredProperties = new Hashtable();
            requiredProperties.Add(CustomSiteColumns.FIELD_DOCSET_DEPARTMNET, CurrentRadicado.DepartamentoUsuario);
            requiredProperties.Add(CustomSiteColumns.FIELD_DOCSET_KIND, TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_TIPOS, GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA));
            this.CreateDocument(parentFolder, this.CurrentContentType, requiredProperties);
            this.CurrentDocumentSet.Folder.Item.Update();
            this.updateMetadata();
            return this.CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
        }

        public override void CreateDocument(string target, string contentTypeName, string radicadoName, Hashtable requiredStartingProperties)
        {
            InitialAssidnedUser = SPContext.Current.Web.CurrentUser.LoginName;
            string libraryName = InitialAssidnedUser.GetUserWithOutDomain();
            CurrentLibrary = libraryName;
            SPList userList = this.CurrentWeb.Lists.TryGetList(libraryName);

            if (userList == null)
                throw new Exception(string.Format(ExceptionConstants.ERROR_BIBLIOTECA_USUARIO_INEXISTENTE, libraryName));

            SPContentTypeId contentType = userList.ContentTypes[contentTypeName].Id;
            string tempName = Guid.NewGuid().ToString();
            CurrentDocumentSet = Office.DocumentSet.Create(userList.RootFolder, tempName, contentType, requiredStartingProperties);
            CurrentDocumentSet.Log(string.Empty, DateTime.Now, TraceableOperation.Radicado, CurrentRadicado.Radicador, string.Empty);
            this.UpdateDocument();

        }

        public override ITransactionResponse NewRadicado()
        {
            string newId = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        Hashtable requiredProperties = new Hashtable();
                        requiredProperties.Add(CustomSiteColumns.FIELD_DOCSET_DEPARTMNET, CurrentRadicado.DepartamentoUsuario);
                        requiredProperties.Add(CustomSiteColumns.FIELD_DOCSET_KIND, TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_TIPOS, GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA));
                        currentWeb.AllowUnsafeUpdates = true;
                        this.CreateDocument(CurrentRadicado.RemitenteInternoId.ToString(), GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA, this.CurrentRadicado.Name, requiredProperties);
                        this.CurrentDocumentSet.Folder.Item.Update();
                        updateMetadata();
                        newId = this.CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
                    }
                }
            });

            ITransactionResponse response = new BaseRadicadoOperationResponse();
            response.Result = true;
            response.ResponseMessage = string.Format(GlobalConstants.SUCCESS_RADICADO_CREATION, "de salida", newId);
            return response;

        }

        public override void updateMetadata()
        {
            DateTime currentDate = DateTime.Now;

            if (CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO] != null && !TryLogTRDChange(currentDate))
                this.LogUpdate();

            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_RADICADO_PADRE] = CurrentRadicado.RadicadoEntrada;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_REMITENTE_INTERNO] = CurrentRadicado.RemitenteInterno;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA] = CurrentRadicado.Cédula;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_NOMBRES] = CurrentRadicado.Nombres;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1] = CurrentRadicado.PrimerApellido;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2] = CurrentRadicado.SegundoApellido;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO] = CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
            CurrentDocumentSet.Folder.Item[SPBuiltInFieldId.Title] = CurrentRadicado.Name;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TIPO_DE_ANEXO] = CurrentRadicado.TipoAnexo;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TRD] = CurrentRadicado.IDTRD.HasValue ? int.Parse(CurrentRadicado.IDTRD.ToString()) : 0;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION] = CurrentRadicado.IDSubSeccion.HasValue ? int.Parse(CurrentRadicado.IDSubSeccion.ToString()) : 0;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO] = CurrentRadicado.Asunto;
            CurrentRadicado.Status = TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_STATUS, GlobalConstants.METADATA_TERM_STATUS_RADICADO);
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS] = CurrentRadicado.Status;
            TaxonomyFieldValue fvCountries = CurrentRadicado.Countries;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_COUNTRY] = fvCountries;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_PHONE] = CurrentRadicado.Teléfono;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_ADDRESS] = CurrentRadicado.Dirección;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_EMAIL] = CurrentRadicado.Email;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DESTINATARIO] = CurrentRadicado.DestinatarioId;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_MEDIO] = CurrentRadicado.MedioRecepción.ToString();
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] = CurrentRadicado.CantidadFolios;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] = CurrentRadicado.CantidadFoliosAnexos;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET] = CurrentRadicado.DepartamentoUsuario;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_KIND] = TermStoreHelper.GetTaxonomyFieldByTerm(GlobalConstants.METADATA_GROUP_NAME, GlobalConstants.METADATA_TERM_TIPOS, GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA);
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT] = CurrentRadicado.Nombres + " " + CurrentRadicado.PrimerApellido;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] = CurrentRadicado.TipoDocumento;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID] = CurrentRadicado.Document_Documental_Type_ID;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN] = CurrentRadicado.MedioDeEnvio;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN_ID] = CurrentRadicado.IDMedioDeEnvío;

            this.CurrentDocumentSet.Folder.Item.Update();
            this.LoadFilesToDocumentSet();
            this.LoadCopysToDocumentSet();
        }

        public override void UpdateRadicado()
        {
            this.CurrentDocumentSet = GetDocumentSet(this.CurrentRadicado.Id.Value);
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            this.CurrentDocumentSet.Folder.Item.Update();
            this.LogUpdate();
            DateTime currentDate = DateTime.Now;
            TryLogTRDChange(currentDate);

            #region Update Radicados Hijos
            if (CurrentRadicado.AttachedDocuments != null)
            {
                AttachedDocumentsFieldValue fieldCurrentValue = CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_ATTACHED_DOCUMENTS] as AttachedDocumentsFieldValue;
                List<string> radicados;
                if (fieldCurrentValue != null)
                {
                    radicados = fieldCurrentValue.AttachedDocuments.ToList();
                    radicados.Add(CurrentRadicado.AttachedDocuments);
                    radicados = radicados.Distinct().ToList();
                    AttachedDocumentsFieldValue fieldValue = new AttachedDocumentsFieldValue(radicados[0]);
                    for (int i = 1; i < radicados.Count; i++)
                    {
                        fieldValue.Add(radicados[i]);
                    }
                    CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_ATTACHED_DOCUMENTS] = fieldValue;
                }
                else
                {
                    fieldCurrentValue = new AttachedDocumentsFieldValue(CurrentRadicado.AttachedDocuments);
                    CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_ATTACHED_DOCUMENTS] = fieldCurrentValue;
                }

            }
            #endregion

            #region Update Copys

            List<int> CurrentCopys = (from SPFile file in CurrentDocumentSet.Folder.Files.OfType<SPFile>()
                                      where file.Item.ContentType.Name == GlobalConstants.CTTN_COPIAS_RADICADO
                                      select file.Item.ID).ToList();

            UpdateCopysToDocumentSet(CurrentCopys);

            #endregion

            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_CEDULA] = CurrentRadicado.Cédula;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_NOMBRES] = CurrentRadicado.Nombres;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1] = CurrentRadicado.PrimerApellido;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2] = CurrentRadicado.SegundoApellido;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TIPO_DE_ANEXO] = CurrentRadicado.TipoAnexo;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_TRD] = CurrentRadicado.IDTRD.HasValue ? int.Parse(CurrentRadicado.IDTRD.ToString()) : 0;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_SUBSECCION] = CurrentRadicado.IDSubSeccion.HasValue ? int.Parse(CurrentRadicado.IDSubSeccion.ToString()) : 0;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_ASUNTO] = CurrentRadicado.Asunto;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_PHONE] = CurrentRadicado.Teléfono;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_ADDRESS] = CurrentRadicado.Dirección;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_EMAIL] = CurrentRadicado.Email;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_MEDIO] = CurrentRadicado.MedioRecepción;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] = CurrentRadicado.CantidadFolios;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] = CurrentRadicado.CantidadFoliosAnexos;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_COUNTRY] = CurrentRadicado.Countries;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET] = CurrentRadicado.DepartamentoUsuario;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] = CurrentRadicado.TipoDocumento;
            CurrentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID] = CurrentRadicado.Document_Documental_Type_ID;

            this.CurrentDocumentSet.Folder.Item.Update();
            //this.RemoveFiles(this.CurrentDocumentSet);
            //this.LoadFilesToDocumentSet();
            SPContext.Current.Web.AllowUnsafeUpdates = false;
        }

        public override string GetTargetLibrary(string target)
        {
            SPUser user = SPContext.Current.Web.AllUsers.GetByID(int.Parse(target));
            return user.LoginName.Split('\\')[1];
        }

        public override RadicadoPersonaSalida GetRadicado(int id)
        {
            RadicadoPersonaSalida r = default(RadicadoPersonaSalida);
            Guid siteGuid = SPContext.Current.Site.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                using (SPSite overridenSecuritySite = new SPSite(siteGuid))
                {
                    using (SPWeb overrideSecurityWeb = overridenSecuritySite.OpenWeb())
                    {
                        SPTimeZoneCollection timeZoneColl = SPRegionalSettings.GlobalTimeZones;
                        var tz = timeZoneColl.OfType<SPTimeZone>().Where(x => x.ID == 35).FirstOrDefault();

                        SPDocumentLibrary library = overrideSecurityWeb.Lists.TryGetList(TargetLibrary) as SPDocumentLibrary;
                        if (library == null) { throw new Exception(string.Format("Verifique que la biblioteca de documentos {0} existe.")); }
                        SPListItem listItem = library.GetItemById(id);
                        if (listItem == null) { throw new Exception(string.Format("No existe un documento con id {1} en la biblioteca {0}", TargetLibrary, id)); }
                        if (listItem.ContentType.Name.Equals(GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA))
                        {

                            r = new RadicadoPersonaSalida();

                            r.Archivado = listItem[CustomSiteColumns.FIELD_DOCUMENT_FILED] == null ? new Nullable<bool>()
                                 : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_FILED]);
                            r.Asunto = listItem[CustomSiteColumns.FIELD_DOCSET_ASUNTO] == null ? string.Empty
                               : listItem[CustomSiteColumns.FIELD_DOCSET_ASUNTO].ToString();
                            r.Cancelado = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CANCEL] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CANCEL]);
                            r.CantidadFolios = listItem[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS] == null ? new Nullable<double>()
                                     : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS]);
                            r.CantidadFoliosAnexos = listItem[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX] == null ? new Nullable<double>()
                                : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_FOLIOS_ANEX]);
                            r.Categories = listItem[CustomSiteColumns.FIELD_DOCUMENT_CATEGORY] == null ? null
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_CATEGORY] as TaxonomyFieldValue;
                            r.Cédula = listItem[CustomSiteColumns.FIELD_DOCUMENT_CEDULA] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_CEDULA].ToString();
                            r.Celular = listItem[CustomSiteColumns.FIELD_DOCUMENT_CELLPHONE] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_CELLPHONE].ToString();
                            r.ChildDocuments = listItem[CustomSiteColumns.FIELD_DOCSET_ATTACHED_DOCUMENTS] as SPFieldMultiColumnValue;
                            r.Copias = listItem[CustomSiteColumns.FIELD_DOCUMENT_COPIESQTY] == null ? new Nullable<double>()
                             : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_COPIESQTY]);
                            r.Countries = listItem[CustomSiteColumns.FIELD_DOCUMENT_COUNTRY] == null ? null
                                    : listItem[CustomSiteColumns.FIELD_DOCUMENT_COUNTRY] as TaxonomyFieldValue;
                            r.Created = Convert.ToDateTime(listItem[SPBuiltInFieldId.Created]);
                            r.DeliveryLogs = listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_LOG] == null ? new List<DeliveryTraceabilityEntry>()
                                : (listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_LOG] as DeliveryTraceabilityFieldValue).Entries;
                            r.DepartamentoUsuario = listItem[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET] == null ? new Nullable<double>()
                                : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET]);
                            r.Description = listItem[CustomSiteColumns.FIELD_DOCSET_DESCRIPCION] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_DESCRIPCION].ToString();
                            r.Destinatario = listItem[CustomSiteColumns.FIELD_DOCUMENT_DESTINATARIO] == null ? string.Empty
                                : new SPFieldLookupValue(listItem[CustomSiteColumns.FIELD_DOCUMENT_DESTINATARIO].ToString()).LookupValue;
                            r.DestinatarioId = listItem[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO] == null ? new Nullable<Int32>()
                                : new SPFieldLookupValue(listItem[CustomSiteColumns.FIELD_DOCSET_DESTINATARIO].ToString()).LookupId;
                            r.Devuelto = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_RETURNED] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_RETURNED]);
                            r.Digitalizado = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CAPTURED] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CAPTURED]);
                            r.Dirección = listItem[CustomSiteColumns.FIELD_DOCUMENT_ADDRESS] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_ADDRESS].ToString();
                            r.Document_Documental_Type_ID = listItem[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID] == null ? new Nullable<Int32>()
                                : Convert.ToInt32(Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_DCOUMENTAL_TYPE_ID]));
                            r.DocumentID = listItem[CustomSiteColumns.FIELD_DOCSET_DOCUMENTID] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_DOCUMENTID].ToString();
                            r.DocumentIDValue = listItem[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString();
                            r.Email = listItem[CustomSiteColumns.FIELD_DOCUMENT_EMAIL] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_EMAIL].ToString();
                            r.Enviado = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT]);
                            r.EnvíoDeCorreo = listItem[CustomSiteColumns.FIELD_MAIL_DELIVERIES] == null ? string.Empty
                                 : listItem[CustomSiteColumns.FIELD_MAIL_DELIVERIES].ToString();
                            r.EnvioRechazo = listItem[CustomSiteColumns.FIELD_DOCUMENT_MOTIVO_RECHAZO] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_MOTIVO_RECHAZO].ToString();
                            r.FechaDeAgendado = listItem[CustomSiteColumns.FIELD_DOCSET_FECHA_AGENDADO] == null ? new Nullable<DateTime>()
                                : Convert.ToDateTime(listItem[CustomSiteColumns.FIELD_DOCSET_FECHA_AGENDADO]);
                            r.FechaDeEnvío = listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_DATE] == null ? new Nullable<DateTime>()
                                 : Convert.ToDateTime(listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_DATE]);
                            r.FechaDeImpresión = listItem[CustomSiteColumns.FIELD_DOCUMENT_PRINTDATE] == null ? new Nullable<DateTime>()
                                : Convert.ToDateTime(listItem[CustomSiteColumns.FIELD_DOCUMENT_PRINTDATE]);
                            r.FechaRespuesta = listItem[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE] == null ? new Nullable<DateTime>()
                                : Convert.ToDateTime(listItem[CustomSiteColumns.FIELD_DOCUMENT_MAXRESPONSEDATE]);
                            r.GuíasDeEnvío = listItem[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] == null ? string.Empty
                                 : listItem[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE].ToString();
                            r.Id = listItem.ID;
                            r.IDMedioDeEnvío = listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN_ID] == null ? new Nullable<double>()
                                 : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN_ID]);
                            r.IDTRD = listItem[CustomSiteColumns.FIELD_DOCUMENT_TRD] == null ? new Nullable<Int32>()
                             : Convert.ToInt32(Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_TRD]));
                            r.IDSubSeccion = listItem[CustomSiteColumns.FIELD_DOCSET_SUBSECCION] == null ? new Nullable<Int32>()
                             : Convert.ToInt32(Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCSET_SUBSECCION]));
                            r.Impreso = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_PRINTED] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_PRINTED]);
                            r.Incluido = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_FILED] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_FILED]);
                            r.LogEntries = listItem[CustomSiteColumns.FIELD_DOCUMENT_TRACEABILITY_LOG] == null ? new List<TraceabilityEntry>()
                             : (listItem[CustomSiteColumns.FIELD_DOCUMENT_TRACEABILITY_LOG] as DocumentTraceabilityFieldValue).Entries;
                            r.MedioDeEnvio = listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN] == null ? string.Empty
                                 : listItem[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN].ToString();
                            r.MedioRecepción = listItem[CustomSiteColumns.FIELD_DOCUMENT_MEDIO] == null ? new Nullable<MedioRecepción>()
                               : (MedioRecepción)Enum.Parse(typeof(MedioRecepción), listItem[CustomSiteColumns.FIELD_DOCUMENT_MEDIO].ToString().Replace(" ", string.Empty));
                            r.Name = listItem[SPBuiltInFieldId.Title] == null ? string.Empty
                                : listItem[SPBuiltInFieldId.Title].ToString();
                            r.NoActa = listItem[CustomSiteColumns.FIELD_DOCUMENT_NIT] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_NIT].ToString();
                            r.Nombres = listItem[CustomSiteColumns.FIELD_DOCUMENT_NOMBRES] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_NOMBRES].ToString();
                            r.NoRadicado = listItem[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_ID_RADICADO].ToString();
                            r.NúmeroExpediente = listItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID].ToString();
                            r.NúmeroTomo = listItem[CustomSiteColumns.FIELD_VOLUME_ID] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_VOLUME_ID].ToString();
                            r.ObservacionEnvio = listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES_ENVIO] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES_ENVIO].ToString();
                            r.Observaciones = listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES].ToString();
                            r.ObservacionesAdministrador = listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES_ADMIN] == null ? string.Empty
                               : listItem[CustomSiteColumns.FIELD_DOCUMENT_OBSERVACIONES_ADMIN].ToString();
                            r.Pesado = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WEIGHT] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WEIGHT]);
                            r.PrimerApellido = listItem[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO1].ToString();
                            r.RadicadoEntrada = listItem[CustomSiteColumns.FIELD_DOCUMENT_RADICADO_PADRE] == null ? string.Empty
                                 : listItem[CustomSiteColumns.FIELD_DOCUMENT_RADICADO_PADRE].ToString();
                            r.Radicador = listItem[CustomSiteColumns.FIELD_DOCUMENT_RADICADOR] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_RADICADOR].ToString();
                            r.Recibido = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED]);
                            r.RecibidoCorrespondencia = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW]);
                            r.RecibidoInterno = listItem[CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION] == null ? new Nullable<bool>()
                                : Convert.ToBoolean(listItem[CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION]);
                            r.Reenvios = listItem[CustomSiteColumns.FIELD_DOCUMENT_RESENTQTY] == null ? new Nullable<double>()
                                 : Convert.ToDouble(listItem[CustomSiteColumns.FIELD_DOCUMENT_RESENTQTY]);
                            r.RemitenteDestinatario = listItem[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_SENDERRECEPT].ToString();
                            r.RemitenteInterno = listItem[CustomSiteColumns.FIELD_DOCUMENT_REMITENTE_INTERNO] == null ? string.Empty
                                 : new SPFieldUserValue(listItem.Web, listItem[CustomSiteColumns.FIELD_DOCUMENT_REMITENTE_INTERNO].ToString()).LookupValue;
                            r.RemitenteInternoId = listItem[CustomSiteColumns.FIELD_DOCUMENT_REMITENTE_INTERNO] == null ? new Nullable<Int32>()
                                : new SPFieldUserValue(listItem.Web, listItem[CustomSiteColumns.FIELD_DOCUMENT_REMITENTE_INTERNO].ToString()).LookupId;
                            r.SegundoApellido = listItem[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_APELLIDO2].ToString();
                            r.Status = listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS] == null ? null
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_STATUS] as TaxonomyFieldValue;
                            r.Teléfono = listItem[CustomSiteColumns.FIELD_DOCUMENT_PHONE] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_PHONE].ToString();
                            r.TipificaciónInicial = listItem[CustomSiteColumns.FIELD_DOCUMENT_INITIAL_TYPE] == null ? new Nullable<TipificaciónInicial>()
                                : (TipificaciónInicial)Enum.Parse(typeof(TipificaciónInicial), listItem[CustomSiteColumns.FIELD_DOCUMENT_INITIAL_TYPE].ToString().Replace(" ", string.Empty));
                            r.Tipo = listItem[CustomSiteColumns.FIELD_DOCSET_KIND] == null ? null
                                : listItem[CustomSiteColumns.FIELD_DOCSET_KIND] as TaxonomyFieldValue;
                            r.TipoAnexo = listItem[CustomSiteColumns.FIELD_DOCUMENT_TIPO_DE_ANEXO] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCUMENT_TIPO_DE_ANEXO].ToString();
                            r.TipoDocumento = listItem[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE] == null ? string.Empty
                               : listItem[CustomSiteColumns.FIELD_DOCUMENT_DOCUMENTAL_TYPE].ToString();
                            r.TipoRadicado = r.Tipo.Label;
                            r.Titulo = listItem[CustomSiteColumns.FIELD_DOCSET_DESCRIPCION] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_DOCSET_DESCRIPCION].ToString();
                            r.UsuarioAsignado = listItem[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] == null ? string.Empty
                                : listItem[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED].ToString();

                            Office.DocumentSet currentDoc = GetDocumentSet(id, overrideSecurityWeb);

                            r.AttachedFiles = (from file in currentDoc.Folder.Files.OfType<SPFile>()
                                               where file.Item.ContentType.Name != GlobalConstants.CTTN_COPIAS_RADICADO
                                               select new FileEntity
                                               {
                                                   CreationDate = tz.UTCToLocalTime(file.TimeCreated.ToUniversalTime()),
                                                   FileContent = file.OpenBinary(),
                                                   FileName = file.Name,
                                                   FileSize = file.OpenBinary().Length / 1024,
                                                   IsMainDocument = ListHelper.ConvertToBoolean(file.Item[CustomSiteColumns.FIELD_DOCUMENT_IS_MAIN] + "")
                                               }).ToList();

                            r.AttachedCopys = (from file in currentDoc.Folder.Files.OfType<SPFile>()
                                               where file.Item.ContentType.Name == GlobalConstants.CTTN_COPIAS_RADICADO
                                               select new DAL.DTOs.ContactsDTO
                                               {
                                                   IdItem = file.Item.ID,
                                                   Id = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_ID] + "",
                                                   Direccion = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_ADDRESS] + "",
                                                   Telefono = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_PHONE] + "",
                                                   Email = file.Item[CustomSiteColumns.FLD_COPY_CONTACT_EMAIL] + "",
                                                   IdMedioEnvio = file.Item[CustomSiteColumns.FLD_COPY_ENVIO_ID] + "",
                                                   MedioEnvio = file.Item[CustomSiteColumns.FLD_COPY_ENVIO_NAME] + "",
                                                   Nombre = file.Item[CustomSiteColumns.FLD_COPY_NAME] + "",
                                                   Representante = file.Item[CustomSiteColumns.FLD_COPY_REPRESENTANTE] + ""
                                               }).ToList();

                        }
                    }
                }
            });
            

            return r;
        }

    }
}
